import * as vscode from "vscode";
import { TurboRenderer } from "./renderer";
import { MermaidLinter } from "./linter";
import { PreviewPanel } from "./preview";

// 添加输出通道
let outputChannel: vscode.OutputChannel;

export function activate(context: vscode.ExtensionContext) {
  // 创建输出通道
  outputChannel = vscode.window.createOutputChannel("Mermaid Vision");
  outputChannel.show();

  outputChannel.appendLine("Mermaid Vision is activating...");

  // 初始化核心模块
  const renderer = new TurboRenderer(context);
  const linter = new MermaidLinter();
  const preview = new PreviewPanel(context.extensionUri, renderer);

  // 注册实时预览面板
  const previewDisposable = vscode.window.registerWebviewViewProvider(
    "mermaidVision.preview",
    preview
  );

  // 自动显示预览面板
  vscode.commands.executeCommand("mermaidVision.preview.focus");

  // 文档变化监听
  const docWatcher = vscode.workspace.onDidChangeTextDocument(async (e) => {
    if (e.document.languageId === "markdown") {
      outputChannel.appendLine("Markdown file changed");
      const code = extractMermaidCode(e.document.getText());
      outputChannel.appendLine("Extracted code: " + code);
      if (code) {
        try {
          outputChannel.appendLine("Rendering code...");
          const [svg, diagnostics] = await Promise.all([
            renderer.render(code),
            linter.check(e.document),
          ]);

          outputChannel.appendLine(
            "SVG generated: " + svg.substring(0, 100) + "..."
          );
          preview.update(svg);
        } catch (err) {
          outputChannel.appendLine("Render error: " + (err as Error).message);
          preview.showError((err as Error).message);
        }
      }
    }
  });

  // 立即处理当前活动文档
  if (vscode.window.activeTextEditor?.document.languageId === "markdown") {
    outputChannel.appendLine("Processing active markdown document");
    const code = extractMermaidCode(
      vscode.window.activeTextEditor.document.getText()
    );
    outputChannel.appendLine("Initial code: " + code);
    if (code) {
      renderer
        .render(code)
        .then((svg) => {
          outputChannel.appendLine("Initial SVG generated");
          preview.update(svg);
        })
        .catch((err) => {
          outputChannel.appendLine(
            "Initial render error: " + (err as Error).message
          );
          preview.showError((err as Error).message);
        });
    }
  }

  // 注册命令和订阅
  context.subscriptions.push(
    previewDisposable,
    docWatcher,
    vscode.commands.registerCommand("mermaidVision.quickFix", () => {
      // 快速修复实现...
    })
  );
}

function extractMermaidCode(text: string): string | null {
  const mermaidBlock = text.match(/```mermaid([\s\S]*?)```/);
  return mermaidBlock ? mermaidBlock[1].trim() : null;
}

export function deactivate() {
  if (outputChannel) {
    outputChannel.dispose();
  }
}
